import { ref, reactive, nextTick, onMounted } from "vue";
import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, FormInstance } from "element-plus";
import { PersonGetAllByPagedAndSort, GetPersonalreportByPagedAndSort, GetReport, GetMoudleKeyValue, SelectPersonalReport } from "@/api/stu/DataScene";
import { getBigDataProcessApi } from "@/api/stu/bigdataprocessing";
import { useRoute } from "vue-router";
import qs from "qs"
export function usePersonCredit() {
  // 分页
  const route = useRoute();
  const RepotFroms = ref();
  const ShowReport = ref<string>("");
  const dataList = ref<any>([]);
  const dataList2 = ref<any>([]);
  const btnloading = ref<boolean>(false);
  const loading = ref<boolean>(false);
  const loading2 = ref<boolean>(false);
  const RepotVisible = ref<boolean>(false);
  const CreditReportVisible = ref<boolean>(false);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    background: true
  });
  const pagination2 = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    },
    {
      label: "姓名",
      prop: "name",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <span>{row.name.substring(0, 1) + "*" + row.name.substring(2)}</span>
      )
    },
    {
      label: "性别",
      prop: "gender",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <el-tag type={
          row.gender ? "warning" : "primary"}>
          {
            row.gender ? "女" : "男"
          }
        </el-tag>
      )
    },
    {
      label: "年龄",
      prop: "age",
      minWidth: 100
    },
    {
      label: "民族",
      prop: "nation",
      minWidth: 100
    },
    {
      label: "身份证号码",
      prop: "idCard",
      minWidth: 200,
      cellRenderer: ({ row }) => (<span>{
        row.idCard.replace(/(\d{14})(\d{4})$/, "$1****")
      }</span>)
    },
    {
      label: "电话号码",
      prop: "phone",
      minWidth: 150,
      cellRenderer: ({ row }) => (<span>{
        row.phone.replace(/(\d{7})(\d{4})$/, "$1****")
      }</span>)
    },
    {
      label: "电子邮箱",
      prop: "email",
      minWidth: 150
    },
    {
      label: "婚姻状况",
      prop: "marriage",
      minWidth: 100
    },
    {
      label: "省份",
      prop: "province",
      minWidth: 200
    },
    {
      label: "家庭地址",
      prop: "homeAddress",
      minWidth: 200
    }, {
      label: "逾期次数",
      prop: "overdueTimes",
      minWidth: 100
    },
    // {
    //   label: "操作",
    //   fixed: "right",
    //   width: 180,
    //   slot: "operation"
    // }
  ];
  const columns2: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    },
    {
      label: "姓名",
      prop: "name",
      minWidth: 200
    },
    {
      label: "报告编号",
      prop: "reportNo",
      minWidth: 300
    },
    {
      label: "查询时间",
      prop: "queryDate",
      minWidth: 300
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];
  const regex = /^[\u4e00-\u9fa5]{2,4}$/;// 校验2-4个字中文
  const regPhone = /^1[3456789]\d{9}$/;
  const regID = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  // 校验申请表单
  const rules = {
    ApplyName: [
      {
        required: true,
        validator: (rule: any, value: any, callback: () => void) => {
          if (regex.test(RepotFrom.ApplyName) === false) {
            return callback(new Error('请输2-4的中文名称'))
          } else {
            // 校验通过
            return callback()
          }
        },
        trigger: ["blur", "change"],
      }
    ],
    ApplyNumber: [
      {
        required: true,
        trigger: ["blur", "change"],
        validator: (rule: any, value: any, callback: () => void) => {
          if (regID.test(RepotFrom.ApplyNumber) === false) {
            return callback(new Error('请输入正确的证件码'))
          } else {
            // 校验通过
            return callback()
          }
        },
      }
    ],
    ApplyPhone: [
      {
        required: true,
        trigger: ["blur", "change"],
        validator: (rule: any, value: any, callback: () => void) => {
          if (regPhone.test(RepotFrom.ApplyPhone) === false) {
            return callback(new Error('请输正确的手机号'))
          } else {
            // 校验通过
            return callback()
          }
        },
      }
    ],
    // AgencyName: [
    //   {
    //     required: true,
    //     validator: (rule: any, value: any, callback: () => void) => {
    //       if (regex.test(RepotFrom.AgencyName) === false) {
    //         return callback(new Error('请输2-4的中文名称'))
    //       } else {
    //         // 校验通过
    //         return callback()
    //       }
    //     },
    //     trigger: ["blur", "change"],
    //   }
    // ],
    // AgencyNumber: [
    //   {
    //     required: true,
    //     trigger: ["blur", "change"],
    //     validator: (rule: any, value: any, callback: () => void) => {
    //       if (regID.test(RepotFrom.AgencyNumber) === false) {
    //         return callback(new Error('请输入正确的证件码'))
    //       } else {
    //         // 校验通过
    //         return callback()
    //       }
    //     },
    //   }
    // ],
    // AgencyPhone: [
    //   {
    //     required: true,
    //     trigger: ["blur", "change"],
    //     validator: (rule: any, value: any, callback: () => void) => {
    //       if (regPhone.test(RepotFrom.AgencyPhone) === false) {
    //         return callback(new Error('请输正确的手机号'))
    //       } else {
    //         // 校验通过
    //         return callback()
    //       }
    //     },
    //   }
    // ],
    ApplySign: [
      {
        required: true,
        validator: (rule: any, value: any, callback: () => void) => {
          if (regex.test(RepotFrom.ApplySign) === false) {
            return callback(new Error('请输2-4的中文名称'))
          } else {
            // 校验通过
            return callback()
          }
        },
        trigger: ["blur", "change"],
      }
    ],
    ApplyDate: [
      {
        required: true,
        message: '请选择日期',
        trigger: 'change',
      }
    ]
  }

  const RepotFrom = reactive({
    ApplyName: "",
    ApplyType: "",
    ApplyNumber: "",
    ApplyPhone: "",
    AgencyName: "",
    AgencyType: "",
    AgencyNumber: "",
    AgencyPhone: "",
    ApplySign: "",
    ApplyDate: ""
  })
  /* 模块一 */
  // 获取征信报告
  async function GetRepot() {
    const data = qs.stringify({ submoduleName: "个人征信中心" })
    const respone = await GetMoudleKeyValue(data);
    RepotVisible.value = true;
  }

  // 关闭表单并初始化
  function CloseApplication(row: FormInstance | undefined) {
    RepotVisible.value = false;
    row.resetFields();
  }

  // 提交申请表单
  function SubmitApplication(row: FormInstance | undefined) {
    (row as any).validate(async valid => {
      if (!valid) return;
      const {
        ApplyName,
        ApplyNumber,
        ApplyPhone,
        AgencyName,
        AgencyNumber,
        AgencyPhone,
        ApplySign,
        ApplyDate
      } = RepotFrom;
      console.log("RepotFrom", RepotFrom)
      // 学生答案
      const StudentAnswer = [
        { "Key": "B0101", "Value": ApplyName },
        { "Key": "B0102", "Value": ApplyNumber },
        { "Key": "B0103", "Value": ApplyPhone },
        { "Key": "B0104", "Value": AgencyName },
        { "Key": "B0105", "Value": AgencyNumber },
        { "Key": "B0106", "Value": AgencyPhone },
        { "Key": "B0107", "Value": ApplyDate },
      ]
      const data = {
        taskId: route.query.taskId,
        planId: route.query.planId,
        name: ApplyName,
        idCard: ApplyNumber,
        phone: ApplyPhone,
        classId: 15,
        queryDate: ApplyDate,
        Signature: ApplySign,
        StudentAnswer: JSON.stringify(StudentAnswer)
      }
      btnloading.value = true;
      const respone = await GetReport(data);
      if (respone.success) {
        ElMessage.success(respone.msg);
        RepotVisible.value = false;
        btnloading.value = false;
        GetreportPagedAndSort()
        return
      }
      ElMessage.error(respone.msg)
      setTimeout(() => {
        btnloading.value = false;
      }, 1500)
    })
  }

  // 分页
  function handleSizeChange(val) {
    GetMyDataSystem()
  }

  function handleCurrentChange(val) {
    GetMyDataSystem()
  }

  // 分页
  function handleSizeChanges(val) {
    GetreportPagedAndSort()
  }

  function handleCurrentChanges(val) {
    GetreportPagedAndSort()
  }
  /* 模块一 end*/
  ////////////////////////////////
  /* 模块二 */
  // 查看征信报告
  function ShowRepot() {

  }
  /* 模块2 end*/

  // 获取个人征信 数据系统 列表
  async function GetMyDataSystem() {
    const res = await PersonGetAllByPagedAndSort({
      planId: route.query.planId,
      taskId: route.query.taskId,
      "pageIndex": pagination.currentPage,
      "pageCount": pagination.pageSize
    });
    if (res.success) {
      pagination.total = res.data.totalCount;
      dataList.value = res.data.items;
      loading.value = false
    } else {
      ElMessage.error(res.msg);
      setTimeout(() => { loading.value = false }, 1500)
    }
  }

  // 获取个人 征信報告 列表
  async function GetreportPagedAndSort() {
    const res = await GetPersonalreportByPagedAndSort({
      taskId: route.query.taskId,
      planId: route.query.planId,
      "pageIndex": pagination2.currentPage,
      "pageCount": pagination2.pageSize
    });
    if (res.success) {
      pagination2.total = res.data.totalCount;
      dataList2.value = res.data.items;
      loading2.value = false
    } else {
      ElMessage.error(res.msg);
      setTimeout(() => { loading2.value = false }, 1500)
    }
    // pagination2.total = res.data.totalCount;
    // dataList2.value = res.data.items;
  }

  // 单独获取taskid
  async function GetTaskId() {
    const data = {
      pageIndex: 1,
      pageCount: 10,
      planId: route.query.planId,
      taskId: route.query.taskId,
      moduleId: JSON.parse(sessionStorage.getItem("moduleId")),
      userId: ""
    }
    const res = await getBigDataProcessApi(data);
    console.log("?", res)
  }
  // 查看个人征信报告详情
  async function CheckCreditReport(row) {
    console.log("show", row)
    const data = {
      "id": row.id,
      "userId": row.userId,
      planId: route.query.planId,
      taskId: route.query.taskId,
    }
    const respone = await SelectPersonalReport(data);
    if (respone.success) {
      CreditReportVisible.value = true;
      nextTick(() => {
        ShowReport.value = respone.data
      })
    } else {
      ElMessage.error(respone.msg)
    }
  }

  onMounted(() => {
    GetMyDataSystem()
    GetreportPagedAndSort()
    // GetTaskId()
  })

  return {
    ShowReport,
    RepotFroms,
    dataList,
    dataList2,
    loading,
    loading2,
    RepotVisible,
    CreditReportVisible,
    pagination,
    pagination2,
    columns,
    columns2,
    rules,
    btnloading,
    RepotFrom,
    GetRepot,
    CheckCreditReport,
    handleSizeChange,
    handleCurrentChange,
    handleSizeChanges,
    handleCurrentChanges,
    CloseApplication,
    SubmitApplication,
    ShowRepot
  }
}
